package com.lb.myeam.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lb.myeam.common.utils.DBUtil;
import com.lb.myeam.common.utils.MD5Util;
import com.lb.myeam.core.dao.DepDao;
import com.lb.myeam.core.dao.impl.DepDaoImpl;
import com.lb.myeam.core.entity.DepEntity;
import com.sun.xml.internal.ws.util.StringUtils;

/**
 * liubiao
 */
public class DepServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DepDao depDao = new DepDaoImpl();

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String act = req.getParameter("act");
		System.out.println("act:" + act);
		if ("login".equals(act)) {
			doLogin(req, resp);
		} else if ("doAdd".equals(act)) {
			doAdd(req, resp);
		} else if ("doList".equals(act)) {
			doList(req, resp);
		} else if ("doUpdate".equals(act)) {
			doUpdate(req, resp);
		} else if ("doDelete".equals(act)) {
			doDelete(req, resp);
		} else if ("isExist".equals(act)) {
			isExist(req, resp);
		}
	}

	public void doLogin(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String depAccount = req.getParameter("account");
		String depPassword = req.getParameter("password");

		// input
		String checkcode = req.getParameter("checkcode").toUpperCase();
		// produce
		String piccode = (String) req.getSession().getAttribute("piccode");

		boolean flag = checkcode.equals(piccode);

		// 先检验验证码
		if (!flag) {
			req.setAttribute("error_msg", "验证码错误！");
			req.getRequestDispatcher("/login.jsp").forward(req, resp);

		} else {// 验证码成功后的操作

			String usernameCookie = null;
			String passwordCookie = null;
			Cookie[] cookies = req.getCookies();
			// 如果存在cookies
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if ("SESSION_LOGIN_USERNAME".equals(cookie.getName())) {
						usernameCookie = cookie.getValue(); // 得到cookie的用户名
					}
					if ("SESSION_LOGIN_PASSWORD".equals(cookie.getName())) {
						passwordCookie = cookie.getValue(); // 得到cookie的密码
					}
				}
				// 如果Cookie中用户名和密码存在
				if (usernameCookie != null && passwordCookie != null) {
					// 判断用户名和密码是否符合
					if (depDao.checkLogin(usernameCookie, passwordCookie)) {
						req.getSession().setAttribute("user_online",
								usernameCookie);
						req.getRequestDispatcher("/ui/index.jsp").forward(req,
								resp);
					} else {
						req.setAttribute("error_msg", "用户名或密码错误！");
						req.getRequestDispatcher("/login.jsp").forward(req,
								resp);
					}
					// Cookie中用户名和密码不存在
				} else {
					// 判断输入的用户名和密码
					if (depDao.checkLogin(depAccount, depPassword)) {
						String host = req.getServerName();
						Cookie cookie = new Cookie("SESSION_LOGIN_USERNAME",
								URLEncoder.encode(depAccount, "utf-8")); // 保存用户名到Cookie
						cookie.setPath("/LiuBiaoEAM");
						cookie.setDomain(host);
						cookie.setMaxAge(99999999);
						resp.addCookie(cookie);

						// 获取是否保存Cookie
						String rememberMe = req.getParameter("rememberMe");
						if (rememberMe == null) {// 不保存Cookie
							// 保存密码到Cookie，注意需要加密一下
							cookie = new Cookie("SESSION_LOGIN_PASSWORD",
									depPassword);
							cookie.setPath("/LiuBiaoEAM");
							cookie.setDomain(host);
							cookie.setMaxAge(0);
							resp.addCookie(cookie);
						} else {// 保存Cookie的时间长度，单位为秒
								// 保存密码到Cookie，注意需要加密一下
							cookie = new Cookie("SESSION_LOGIN_PASSWORD",
									depPassword);
							cookie.setPath("/LiuBiaoEAM");
							cookie.setDomain(host);
							cookie.setMaxAge(999999);
							resp.addCookie(cookie);
						}

						req.getSession()
								.setAttribute("user_online", depAccount);
						req.getRequestDispatcher("/ui/index.jsp").forward(req,
								resp);

					}
				}
				// 如果cookie不存在
			} else {

				// 判断输入的用户名和密码
				if (depDao.checkLogin(depAccount, depPassword)) {
					String host = req.getServerName();
					Cookie cookie = new Cookie("SESSION_LOGIN_USERNAME",
							URLEncoder.encode(depAccount, "utf-8")); // 保存用户名到Cookie
					cookie.setPath("/LiuBiaoEAM");
					cookie.setDomain(host);
					cookie.setMaxAge(99999999);
					resp.addCookie(cookie);

					// 获取是否保存Cookie
					String rememberMe = req.getParameter("rememberMe");
					if (rememberMe == null) {// 不保存Cookie
						// 保存密码到Cookie，注意需要加密一下
						cookie = new Cookie("SESSION_LOGIN_PASSWORD",
								depPassword);
						cookie.setPath("/LiuBiaoEAM");
						cookie.setDomain(host);
						cookie.setMaxAge(0);
						resp.addCookie(cookie);
					} else {// 保存Cookie的时间长度，单位为秒
							// 保存密码到Cookie，注意需要加密一下
						cookie = new Cookie("SESSION_LOGIN_PASSWORD",
								depPassword);
						cookie.setPath("/LiuBiaoEAM");
						cookie.setDomain(host);
						cookie.setMaxAge(999999);
						resp.addCookie(cookie);
					}

					req.getSession()
							.setAttribute("user_online", usernameCookie);
					req.getRequestDispatcher("/ui/index.jsp")
							.forward(req, resp);

				} else {
					req.setAttribute("error_msg", "用户名或密码错误！");
					req.getRequestDispatcher("/login.jsp").forward(req, resp);
				}

			}

		}

	}

	public void doAdd(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String id = req.getParameter("id");
		String account = req.getParameter("account");
		String password = req.getParameter("password");
		String name = req.getParameter("name");
		System.out.println("id:" + id);
		System.out.println("account:" + account);
		System.out.println("password:" + password);
		System.out.println("name:" + name);
		DepEntity dep = new DepEntity(id, account, password, name);
		DepDao dao = new DepDaoImpl();
		dao.addDep(dep);
		req.getRequestDispatcher("/crud/add.jsp").forward(req, resp);
	}

	public void doList(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<DepEntity> list = depDao.query(null);
		req.setAttribute("list", list);
		req.getRequestDispatcher("/crud/list.jsp").forward(req, resp);
	}

	public void doUpdate(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String id = req.getParameter("id");
		String account = req.getParameter("account");
		String password = req.getParameter("password");
		String name = req.getParameter("name");
		System.out.println("id:" + id);
		System.out.println("account:" + account);
		System.out.println("password:" + password);
		System.out.println("name:" + name);
		DepEntity dep = new DepEntity(id, account, password, name);
		depDao.updateDep(dep);
		req.getRequestDispatcher("/crud/update.jsp").forward(req, resp);
	}

	public void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		depDao.deleteDep(req.getParameter("id"));
		doList(req, resp);
	}

	public void isExist(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String val = request.getParameter("id");
		PrintWriter writer = response.getWriter();

		boolean exist = depDao.isExist(val);
		if (exist) {
			writer.write("error");
		} else {
			writer.write("ok");
		}
		writer.flush();
		writer.close();

	}

}
